﻿using System;
using System.Security;
using BusinessLogic.Connectivity.Entities;
using BusinessLogic.Managers.Processing.ProcessingExceptions;
using DataAccess.Services;

namespace BusinessLogic.Managers.Processing
{
	internal class ProcessingExceptionCatcher : ProcessingExceptionCatcherBase
	{
		public override void Execute(Action<object, IServiceManager> func, object document, IServiceManager serviceManager, DocumentEnvelope envelope)
		{
			try
			{
				func(document, serviceManager);
			}
			catch
			{
				envelope.Status = DocumentEnvelopeStatus.NotAccepted;

				try
				{
					throw;
				}
				catch (AccountCodeDoesNotExistException e)
				{
					envelope.RejectionReason = string.Format("Account '{0}' doesn't exist.", e.AccountCode);
				}
				catch (CurrencyDoesntExistException e)
				{
					envelope.RejectionReason = string.Format("Currency with '{0}' doesn't exist.", e.Currency.Code);
				}
				catch (DocumentFormatException)
				{
					envelope.RejectionReason = "The document sent was not formatted correctly.";
				}
				catch (DuplicateDocumentNumberException e)
				{
					envelope.RejectionReason = string.Format("The document with number '{0}' already present in the system.",
															 e.DocumentNumber);
				}
				catch (LowBalanceException)
				{
					envelope.RejectionReason = "The payer account balance is too low to process the document.";
				}
				catch (NotSupportedDocumentTypeException e)
				{
					envelope.RejectionReason = e.Message;
				}
				catch(SecurityException ex)
				{
					envelope.RejectionReason = ex.Message;
				}
				catch (Exception e)
				{
					if (string.IsNullOrEmpty(envelope.RejectionReason))
					{
						envelope.RejectionReason = string.Format("Unhandled exception has been thrown with message: {0}.", e.Message);
					}
				}
			}
		}
	}
}
